<template>
    <div class="" v-if="state !== 'hidden'">

        <el-form ref="form" :model="form" :label-width="'write' == state ? '115px':'auto'" :class="'write' == state ? 'write-form':'read-form'"
                 :label-position="'write' == state ? 'top':'left'">
            <div class="card-wrap flex-column justify-end card-padding">
                <div class="card-title-wrap">
                    <span>基本信息</span>
                    <span></span>
                </div>

                <el-row :gutter="30">
                    <el-col :span="8">
                        <el-form-item label="供应商名称:" prop="supplierName"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请输入供应商名称',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, form.supplierName, callback)
                                       }:{}">
                            <el-input maxlength="50" v-if="'write' == state" v-model="form.supplierName" placeholder="请输入供应商名称"></el-input>
                            <span v-else>{{form.supplierName|filterNull}}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="业务分类:" prop="businessType"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择业务分类',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, form.businessType, callback)
                                       }:{}">
                            <el-select filterable v-if="'write' == state"
                                @change="busChange"
                                v-model="form.businessType" clearable style="width: 100%">
                                <template v-for="dict in dict.type.supplier_business_type">
                                    <el-option :label="dict.label" :value="dict.label" :key="dict.label"></el-option>
                                </template>
                            </el-select>
                            <span v-else>
                                {{form.businessType|filterNull}}
<!--                                <dict-tag-->
<!--                                :options="dict.type.supplier_business_type"-->
<!--                                :value="form.businessTypeCode"/>-->
                            </span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="供应商类型:" prop="supplierTypeCode"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择供应商类型',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, form.supplierTypeCode, callback)
                                       }:{}">
                            <el-radio-group
                                @change="supTypeChange"
                                v-if="'write' == state" v-model="form.supplierTypeCode">
                                <template v-for="dict in dict.type.supplier_type">
                                    <el-radio :label="dict.value">{{ dict.label }}</el-radio>
                                </template>
                            </el-radio-group>
                            <span v-else><dict-tag
                                :options="dict.type.supplier_type"
                                :value="form.supplierTypeCode"/></span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="状态:" prop="availableStatus"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择状态',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, form.availableStatus, callback)
                                       }:{}">
                            <el-radio-group v-if="'write' == state" v-model="form.availableStatus">
                                <template v-for="dict in dict.type.supplier_status">
                                    <el-radio :label="dict.value">{{ dict.label }}</el-radio>
                                </template>
                            </el-radio-group>
                            <span v-else><dict-tag
                                :options="dict.type.supplier_status"
                                :value="form.availableStatus"/></span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="联系人:" prop="contact"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请输入联系人',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, form.contact, callback)
                                       }:{}">
                            <el-input maxlength="50" v-if="'write' == state" v-model="form.contact" placeholder="请输入联系人"></el-input>
                            <span v-else>{{form.contact|filterNull}}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="联系电话:" prop="contactPhone"
                                      :rules="'write' == state ? [{
                                         required: true,
                                         message: '请输入联系电话',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, form.contactPhone, callback)
                                       }, { pattern: /^(1[3456789]\d{9}|[0-9]{5,12})$/, message: '手机号码格式不正确', trigger: 'blur' }
                                       ]:{}">

                            <el-input v-if="'write' == state" clearable
                                      @input="value=>form.contactPhone=value.replace(/[^\d]/g,'')"
                                      :maxlength="12" v-model="form.contactPhone"
                                      placeholder="请输入联系电话"></el-input>
                            <span v-else>{{form.contactPhone|filterNull}}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="供应商法人:" prop="legalPerson">
                            <el-input maxlength="50" v-if="'write' == state" v-model="form.legalPerson" placeholder="请输入供应商法人"></el-input>
                            <span v-else>{{form.legalPerson|filterNull}}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="1==form.supplierTypeCode ? '身份证号:':'统一社会信用代码'" prop="taxpayerIdentityNumber"
                                      :rules="'write' == state ? [{
                                         required: true,
                                         message: 1==form.supplierTypeCode ? '请输入身份证号':'请输入统一社会信用代码',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, form.taxpayerIdentityNumber, callback)
                                       }, 1==form.supplierTypeCode?{}:{ pattern: /^[A-Z0-9]{15}$|^[A-Z0-9]{17}$|^[A-Z0-9]{18}$|^[A-Z0-9]{20}$/, message: '统一社会信用代码格式不正确', trigger: 'blur' }
                                       ]:{}">
                            <el-input v-if="'write' == state" v-model="form.taxpayerIdentityNumber"
                                      maxlength="20" clearable
                                      @input="value=>form.taxpayerIdentityNumber=value.replace(/[^\w_]/g, '')"
                                      placeholder="请输入"></el-input>
                            <span v-else>{{form.taxpayerIdentityNumber|filterNull}}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="城市:" prop="cityName">
                            <ProvinceCity v-if="'write' == state" v-model="form.citydata"
                                          placeholder="请选择城市" ref="citySelect"
                                          :showAllLevels="false"
                                          @change="citySelectionChange"></ProvinceCity>
                            <span v-else>{{form.cityName|filterNull}}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="详细地址:" prop="detailAddr">
                            <el-input maxlength="50" v-if="'write' == state" v-model="form.detailAddr" placeholder="请输入详细地址"></el-input>
                            <span v-else>{{form.detailAddr|filterNull}}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="签订协议:" prop="protocolTypeCode">
                            <el-select filterable v-if="'write' == state"
                                @change="protoChange"
                                v-model="form.protocolTypeCode" clearable>
                                <template v-for="dict in dict.type.supplier_protocol_type">
                                    <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                                </template>
                            </el-select>
                            <span v-else><dict-tag
                                :options="dict.type.supplier_protocol_type"
                                :value="form.protocolTypeCode"/></span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="合约期限:" prop="contractStartTime">
                            <el-date-picker v-if="'write' == state"
                                v-model="timeRange"
                                type="daterange"
                                align="left"
                                unlink-panels
                                range-separator="至"
                                value-format="yyyy-MM-dd"
                                format="yyyy-MM-dd"
                                start-placeholder="开始时间"
                                end-placeholder="结束时间">
                            </el-date-picker>
                            <span v-else>{{form.contractStartTime|filterNull}}-{{form.contractEndTime|filterNull}}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="供应商类别:" prop="supplierTypeSelect" :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择供应商类别',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, form.supplierTypeSelect, callback)
                                       }:{}">
                        <el-select v-if="'write' == state" filterable v-model="form.supplierTypeSelect" clearable style="width: 100%">
                          <template v-for="dict in dict.type.basic_classification_customers">
                            <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                          </template>
                        </el-select>
                        <span v-else><dict-tag
                          :options="dict.type.basic_classification_customers"
                          :value="form.supplierTypeSelect"/></span>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="上传营业执照:" prop="businessLicenseFrontImg"
                                      :rules="'write' == state ? {
                                         required: 2==form.supplierTypeCode,
                                         message: '请上传营业执照',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, form.businessLicenseFrontImg, callback)
                                       }:{}">
                            <div class="flex">
                                <ImageCommon :up-type="2" :disabled="'write' != state" info="营业执照正面" @input="imageChange"
                                             :limit="1" v-model="form.businessLicenseFrontImg"></ImageCommon>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>

        </el-form>

    </div>
</template>

<script>


import ProvinceCity from "@/views/components/provinceCity/index.vue";
import {v4 as uuid_v1} from "uuid";
import {recognitionBusinessLicense2, recognitionDrivingLicense, recognitionIdCard} from "@/api/memberManage/memberList";

export default {
    components: {ProvinceCity},
    dicts: ['supplier_business_type', 'supplier_type', 'supplier_status', 'supplier_protocol_type', 'basic_classification_customers'],
    props:{
        value: {
            default: {},
        },
        state: {
            default: "write",
        },
    },
    computed:{
        form:{
            get() {
                console.log('this.value2', this.value)
                return this.value;
            },
            set(value) {
                console.log('set===>', value)
                this.$emit("input", value);
            },
        },

    },
    watch: {
        form: {
            handler(newVal, oldVal) {
                // if(this.isFirstInner){
                //   if('write'==this.state && !this.form.supplierTypeSelect){
                //     this.$set(this.form, 'supplierTypeSelect', '0202')
                //   }
                //   this.isFirstInner = false
                // }
                if (this.isFirstChange && newVal != null && newVal.supplierId != null) {
                    this.isFirstChange = false

                    console.log('首次改变', newVal)
                    //下标0为一级菜单value
                    this.$set(this.form, 'citydata', [])
                    if(this.form.cityId && this.form.cityId != null){
                        this.$set(this.form.citydata, 0, this.form.provinceId)
                        this.$set(this.form.citydata, 1, this.form.cityId)
                    }

                    // this.form.citydata[0] = this.form.provinceId;
                    // //下标1为二级菜单value
                    // this.form.citydata[1] = this.form.cityId;
                    if(this.form.contractStartTime && this.form.contractEndTime){
                        this.$set(this, 'timeRange', [this.form.contractStartTime, this.form.contractEndTime])
                    }else {
                        this.$set(this, 'timeRange', [])
                    }
                    // this.timeRange = [this.form.contractStartTime, this.form.contractEndTime]
                    this.$forceUpdate()
                    // this.$set(this.form, 'businessTypeCodeList', this.form.businessTypeCode && this.form.businessTypeCode.split(","))
                    // this.$set(this.form, 'protocolTypeCodeList', this.form.protocolTypeCode && this.form.protocolTypeCode.split(","))

                }
            },
            deep: true,
            immediate: true,
        },
    },
    mounted() {
      if('write'==this.state && !this.form.supplierTypeSelect){
        this.$set(this.form, 'supplierTypeSelect', '0202')
      }
    },
    data() {
        return {
            timeRange: [],
            isFirstChange:true,
            isFirstInner:true,
        };
    },
    methods: {
        imageChange() {
            if(!this.form.businessLicenseFrontImg){
                return
            }
            if(this.state != 'write'){
                return;
            }
            let that = this
            //识别营业执照
            // this.buttonLoading = true;
            recognitionBusinessLicense2(this.form.businessLicenseFrontImg).then(res => {
                if (res.code == '200') {
                    for (const dataKey in res.data) {
                        if (res.data[dataKey] != undefined && res.data[dataKey] != null && res.data[dataKey] != '') {
                            // that.form[dataKey] = res.data[dataKey]
                            that.$set(that.form, dataKey, res.data[dataKey])
                        }
                    }
                    that.$forceUpdate();
                } else {
                    // that.form.businessLicenseFrontImg = null
                }
            }).catch(e => {
                // that.form.businessLicenseFrontImg = null
            }).finally(f => {
                // this.buttonLoading = false;
            })
        },
        busChange(val){
            let find = this.dict.type.supplier_business_type.find(item=>item.label==val);
            if(find){
                this.form.businessTypeCode = find.value
            }else {
                this.form.businessTypeCode = null
            }
            this.$forceUpdate()
        },
        supTypeChange(val){
            let find = this.dict.type.supplier_type.find(item=>item.value==val);
            if(find){
                this.form.supplierType = find.label
            }else {
                this.form.supplierType = null
            }
            this.$forceUpdate()
        },
        protoChange(val){
            let find = this.dict.type.supplier_protocol_type.find(item=>item.value==val);
            if(find){
                this.form.protocolType = find.label
            }else {
                this.form.protocolType = null
            }
            this.$forceUpdate()
        },
        citySelectionChange(val) {
            if (val.length > 0) {
                const nodes = Array.from(val, item => ({
                    value: item.value,
                    label: item.label,
                    pv: item.parent.value,
                    pl: item.parent.label
                }))
                this.form.provinceId = nodes[0].pv
                this.form.provinceName = nodes[0].pl
                this.form.cityId = nodes[0].value
                this.form.cityName = nodes[0].label
            } else {
                this.form.provinceId = null
                this.form.provinceName = null
                this.form.cityId = null
                this.form.cityName = null
            }
        },


        validData(rule, value, callback) {
            // console.log('aaa', rule, value, callback)
            if (rule.required && !value) {
                // this.$modal.msgError(`未填写${value}`);
                callback(new Error(rule.message));
            } else {
                callback();
            }
        },


        async valid(type) {

            this.form.contractStartTime = this.timeRange && this.timeRange[0] ? this.timeRange[0] : ''
            this.form.contractEndTime = this.timeRange && this.timeRange[1] ? this.timeRange[1] : ''

            // this.form.businessTypeCode = this.form.businessTypeCodeList.join(",")
            // this.form.protocolTypeCode = this.form.protocolTypeCodeList.join(",")

          console.log('aa', this.form)

            if(1===type){
                return true
            }

            // this.form.workId = this.form.id
            return new Promise((resolve)=>{
                if('write'==this.state){
                    this.$refs["form"].validate(valid => {
                        resolve(valid);
                    });
                }else {
                    resolve(true)
                }
            })
        },
    }
};
</script>


<style lang="scss" scoped>
::v-deep .el-form--label-top .el-form-item__label {
    padding: 0;
}

::v-deep .read-form .el-form-item__label-wrap,
::v-deep .read-form .el-form-item__content {
    margin-left: 0 !important;
}
.el-descriptions{
    margin: 0 -15px;
}
</style>
